using System.Xml.Serialization;
using HengTong.Kingdee.WSExportMaterialFacadeSrvProxyService;

namespace HengTong.Kingdee.Connected_Services.WSExportMaterialFacadeSrvProxyService
{
    /// <summary>
    /// 物料数据扩展方法
    /// </summary>
    public static class MaterialDataExtensions
    {
        /// <summary>
        /// 将 exportMatetialDataResponse 转换为强类型的 MaterialDataInfo 列表
        /// </summary>
        public static List<MaterialDataInfo> ToMaterialDataList(this exportMatetialDataResponse response)
        {
            var result = new List<MaterialDataInfo>();
            if (response?.exportMatetialDataReturn == null)
            {
                return result;
            }

            var serializer = new XmlSerializer(typeof(MaterialDataInfo));
            foreach (var item in response.exportMatetialDataReturn)
            {
                // object[] 中的每个元素实际上是 string 类型的 XML
                var xmlString = item?.ToString();
                if (string.IsNullOrWhiteSpace(xmlString))
                {
                    continue;
                }

                try
                {
                    using var reader = new StringReader(xmlString);
                    var dataInfo = (MaterialDataInfo)serializer.Deserialize(reader);
                    if (dataInfo != null)
                    {
                        result.Add(dataInfo);
                    }
                }
                catch (Exception ex)
                {
                    // 可以记录日志或抛出异常，根据需要处理
                    throw new InvalidOperationException($"解析物料数据失败: {ex.Message}", ex);
                }
            }

            return result;
        }

        /// <summary>
        /// 将单个 XML 字符串转换为 MaterialDataInfo 对象
        /// </summary>
        public static MaterialDataInfo ToMaterialData(this string xmlString)
        {
            if (string.IsNullOrWhiteSpace(xmlString))
            {
                return null;
            }

            var serializer = new XmlSerializer(typeof(MaterialDataInfo));
            using var reader = new StringReader(xmlString);
            return (MaterialDataInfo)serializer.Deserialize(reader);
        }
    }
}

